# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://gateway.paytech88.com/gateway/payment'
_QUERY_GATEWAY = 'https://query.paytech88.com/gateway/query'

APP_CONF = {
    '681618606': {
        'API_KEY': '50E5A011E38FABE0E0B5FD8BB8627567'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('partner_id', app_id),
        ('version', 'V4.0.1'),
        ('input_charset', 'UTF-8'),
        ('sign_type', 'MD5'),
        ('service_name', 'PTY_ONLINE_PAY'),
        ('out_trade_no', pay.id),
        ('order_amount', '%.2f' % pay_amount),
        ('out_trade_time', local_now().strftime('%Y-%m-%d %H:%M:%S')),
        ('pay_type', 'QUICK_PAY'),
        ('bank_code', 'QPAY_UNIONPAY'),
        ('summary', 'test'),
        ('return_url', '{}/pay/api/{}/paytechnew/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('notify_url', '{}/pay/api/{}/paytechnew/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)),
    ))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        charge_resp.update({
            'charge_info': response.text,
        })
        _LOGGER.info("paytechnew data after charge: %s", response.text)
    else:
        _LOGGER.warn('paytechnew data error, status_code: %s', response.status_code)
    return charge_resp


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("paytechnew sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def check_notify_sign(request):
    data = dict(request.POST.iteritems())
    _LOGGER.info("paytech notify data: %s", data)
    app_id = data['partner_id']
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('paytechnew event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['order_status'])
    mch_id = pay.mch_id
    trade_no = data['order_sn']
    total_fee = float(data['order_amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('paytechnew check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('partner_id', app_id),
        ('version', 'V4.0.1'),
        ('input_charset', 'UTF-8'),
        ('sign_type', 'MD5'),
        ('service_name', 'PTY_TRADE_QUERY'),
        ('out_trade_no', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        data = json.loads(response.text)
        print data
        if data['respCode'] == 'RESPONSE_SUCCESS':
            data = data['respResult']
            verify_notify_sign(data, api_key)

            trade_status = int(data['order_status'])
            trade_no = data['order_sn']
            total_fee = float(data['order_amount'])

            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }

            if trade_status == 1:
                _LOGGER.info('paytechnew query order success, mch_id:%s pay_id:%s',
                             pay_order.mch_id, pay_order.id)
                res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                               total_fee, trade_no, extend)
                if res:
                    # async notify
                    async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('paytechnew data error, status_code: %s', response.status_code)
